//
//  QDPayTypePickerView.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/2.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit


protocol QDPayTypePickerViewDelegate: class {
    /// 选择后的回调
    func payTypePickerView(view: QDPayTypePickerView, select type: QDPayType)
}



extension QDPayTypePickerViewDelegate {
    /// 选择后的回调
    func payTypePickerView(view: QDPayTypePickerView, select type: QDPayType) {}
}


/// 支付方式选择界面
final class QDPayTypePickerView: NWPopWindow {

    /// 数据源
    private let titles = ["微信支付","支付宝支付","银联支付"]
    private let titelImages = ["pt_weixin","pt_ali","pt_yinlian"]
    private let types: [QDPayType] = [.Weixin,.ALiPay,.Union]//最后一个仅为了次数，不做实际作用
    private var currentIndex = 0 //默认第一个
    
    /// 底层的白色装载视图
    private let containerView = UIView()
    /// 关闭按钮
    private let closeButton = UIButton()
    /// 标题
    private let titleLabel = UILabel()
    /// 列表展示
    private let tableView = UITableView()
    /// 用于强引用
    private var strongSelf: QDPayTypePickerView?
    /// 下方确认支付的按钮
    private var sureButton = UIButton()
    /// 代理对象
    weak var typeDelegate: QDPayTypePickerViewDelegate?

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        tableView.rowHeight = 56
        
        containerView.backgroundColor = .white
        containerView.layer.cornerRadius = 16
        containerView.frame = CGRect(x: 0, y: ritl_height, width: ritl_width, height: 48 + tableView.rowHeight * 3 + (5 + 46)/*确认按钮以及间距*/ + (hasPhoneHeader() ? BarDistance.TabBar.safeDistance : 7.5)/*常用尺寸底部留边*/ + 16/*需要加上圆角*/)
        
        closeButton.adjustsImageWhenHighlighted = false
        closeButton.setImage("pt_close".namedImage, for: .normal)
        closeButton.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
        
        titleLabel.text = "选择支付方式"
        titleLabel.font = Font.regular.font(size: 16)
        titleLabel.textColor = QDColors.black
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        
        sureButton.setTitle("确认支付", for: .normal)
        sureButton.setTitleColor(.white, for: .normal)
        sureButton.titleLabel?.textAlignment = .center
        sureButton.titleLabel?.font = Font.regular.font(size: 18)
        sureButton.backgroundColor = QDColors.theme
        sureButton.layer.cornerRadius = 4
        sureButton.clipsToBounds = true
        sureButton.addTarget(self, action: #selector(sureButtonDidTap), for: .touchUpInside)
        
        contentView.addSubview(containerView)
        containerView.addSubview(closeButton)
        containerView.addSubview(titleLabel)
        containerView.addSubview(tableView)
        containerView.addSubview(sureButton)
        
        closeButton.snp.makeConstraints { (make) in
            make.height.width.equalTo(24)
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(16)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(13)
        }
        
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(48)
            make.right.left.equalToSuperview()
            make.bottom.equalTo(sureButton).inset(5)
        }
        
        
        sureButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.height.equalTo(46)
            make.bottom.equalToSuperview().inset((hasPhoneHeader() ? BarDistance.TabBar.safeDistance : 7.5) + 16/*隐藏的圆角区域*/)
        }

        
        tableView.register(QDPayTypePickerCell.self, forCellReuseIdentifier: "cell")
        
        //默认为微信
        tableView.selectRow(at: IndexPath(row: currentIndex, section: 0), animated: false, scrollPosition: .none)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    // MARK: Super
    override func showAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
            self.containerView.ritl_originY = self.ritl_height - self.containerView.ritl_height + self.containerView.layer.cornerRadius - BarDistance.TabBar.safeDistance
        }, completion: nil)
    }
    
    
    override func dismissAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
            self.containerView.ritl_originY = self.ritl_height
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    /// 立马消失
    @objc func dimissAtOnce(){
        strongSelf = self
        self.containerView.ritl_originY = self.ritl_height
        self.removeFromSuperview()
        strongSelf = nil
    }
    
    // MARK: @objc
    
    /// 关闭按钮点击
    @objc func closeButtonDidTap(){
        dismissAnimated()
    }
    
    /// 确认支付按钮点击
    @objc func sureButtonDidTap(){
        if let delegate = typeDelegate {
            delegate.payTypePickerView(view: self, select: types[currentIndex])
        }
    }
}



extension QDPayTypePickerView : UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let typeCell = cell as? QDPayTypePickerCell {
            
            let maxIndex = titles.count - 1
            
            /// 赋值
            typeCell.headerImageView.image = titelImages[indexPath.row].namedImage
            typeCell.titleLabel.text = titles[indexPath.row]
            typeCell.bottomLineView.isHidden = (indexPath.row == maxIndex)//最后一行不要下划线
            typeCell.selectImageView.isHidden = false
            typeCell.reminderLabel.isHidden = true
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentIndex = indexPath.row
    }
}
